package com.fy.springmvc2.service.impl;

import com.fy.springmvc2.dao.UserDao;
import com.fy.springmvc2.entity.User;
import com.fy.springmvc2.service.intf.UserService;
import com.fy.springmvc2.vo.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao dao;

    @Override
    public int save(User user) {

         return dao.add(user);

    }

    @Override
    public List<User> selectAll() {
        List<User> users = dao.queryAll();
        return users;
    }

    // 业务层的登录方法
    @Override
    public User login(String name, String password) {
        List<User> users = dao.selectByName(name);
        for (User user:users) {
            if (Objects.equals(password,user.getPassword())){
                return user;
            }
        }
        return null;
    }

    @Override
    public PageInfo<User> selectPage(Integer pageIndex, Integer pageSize) {

        PageHelper.startPage(pageIndex,pageSize);
        List<User> users = dao.queryAll();
        return new PageInfo<>(users);

    }

    @Override
    public R delete(Integer id) {
        if (id>0){
            dao.deleteById(id);
            return R.ok(0);
        }
        return R.fail("-1");
    }

    @Override
    public User selectById(Integer id) {
        return dao.selectOne(id);
    }

    @Override
    public int update(User user) {
        return dao.update(user);
    }


}
